package com.ccx.coachsite.ui.manage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.ccx.coachsite.bus.Account;
import com.ccx.coachsite.bus.AccountMgr;
import com.ccx.coachsite.bus.AnalysisInfo;
import com.ccx.coachsite.bus.CustomInfo;
import com.ccx.coachsite.bus.CustomMessage;
import com.ccx.coachsite.bus.DateParams;
import com.ccx.coachsite.bus.ExpertMessage;
import com.ccx.coachsite.bus.JSONTextUtils;
import com.ccx.coachsite.bus.ManageInfo;
import com.ccx.coachsite.bus.RankInfo;
import com.ccx.coachsite.bus.SalaryInfo;
import com.ccx.coachsite.bus.ShareGroupInfo;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.HttpRequest;
import com.ccx.coachsite.http.UrlConfig;
import com.ccx.coachsite.util.ContactInfo;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;

public class ManageProvider {
	private int errorCode = 200;
	private String lastErrorMessage;
	private static ManageProvider instance;

	public static ManageProvider getInstance() {
		if (instance == null)
			instance = new ManageProvider();
		return instance;
	}

	public int getLastErrorCode() {
		return errorCode;
	}

	public String getLastErrorMessage() {
		return lastErrorMessage;
	}

	public boolean checkContacts(Context context, List<ContactInfo> lstContacts) {
		boolean result = false;
		try {
			// String userId = SharedPreferencesUtil.getValue(context,
			// SharedKey.Shared_UserId_Key, "");
			String firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.ManageQueryContactUrlKey);

			String message = "";
			for (int i = lstContacts.size() - 1; i >= 0; i--) {
				message += lstContacts.get(i).getPhone() + ",";
				lstContacts.get(i).setApply(false);
			}
			if (message.length() > 0)
				message = message.substring(0, message.length() - 1);

			HashMap<String, Object> mMaps = new HashMap<String, Object>();
			mMaps.put("mobile", message);
			// firendUrl += "?mobile="+message;
			BaseResp br = HttpRequest.DoHttpRepuestPost(firendUrl, mMaps);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONArray respsonList = jsonObject.getJSONArray("response");
				if (respsonList != null && respsonList.length() > 0) {
					result = true;
					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject jsonObj = respsonList.getJSONObject(i);
						String phone = jsonObj.getString("mobile");
						for (int j = lstContacts.size() - 1; j >= 0; j--) {
							if (lstContacts.get(j).getPhone().equals(phone)) {
								if (jsonObj.isNull("isApply")
										|| jsonObj.getInt("isApply") == 1) {
									lstContacts.remove(j);
									// lstContacts.get(j).setApply(true);
									break;
								}
							}
						}
					}

				}

			} else {
				result = false;
			}
		} catch (Exception e) {
			result = false;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return result;
	}

	public CustomMessage getCustomMessage(Context context, Account account,
			CustomInfo cinfo) {
		CustomMessage mApp = new CustomMessage();
		mApp.setMobile(cinfo.getTianYi());
		if (!StringUtil.isEmpty(cinfo.getIcon()))
			mApp.setIcon(UrlConfig.ImageBaseUrl + cinfo.getIcon());
		try {
			String firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.ManageQueryCustomUrl);
			firendUrl += "?mobile=" + cinfo.getTianYi();
			BaseResp br = HttpRequest.DoHttpRequest(firendUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				cinfo.setId(respsonObject.getInt("userId"));
				mApp.setId(respsonObject.getInt("userId"));
				if (StringUtil.isEmpty(mApp.getIcon()) && !respsonObject.isNull("icon"))
					mApp.setIcon(respsonObject.getString("icon"));

				mApp.setAppCount(respsonObject.getInt("collection"));
				mApp.setTurCount(respsonObject.getInt("collection1"));
				// JSONArray respsonList =
				// respsonObject.getJSONArray("leaveMessage");
				List<ExpertMessage> rankList = new ArrayList<ExpertMessage>();
				/*
				 * for (int i = 0; i < respsonList.length(); i++) { JSONObject
				 * obj = respsonList.getJSONObject(i); ExpertMessage info = new
				 * ExpertMessage(); info.setId(obj.getInt("id"));
				 * info.setContent(obj.getString("message"));
				 * info.setTime(obj.getString("messageTime")); String userName =
				 * obj.getString("receiver"); if(!StringUtil.isEmpty(userName))
				 * { info.setCreator(obj.getString("receiver")); if
				 * (!userName.equals(account.getUsername()))
				 * info.setIcon(cinfo.getIcon()); else {
				 * 
				 * info.setCreator("我"); info.setIcon(account.getOwerIcon()); }
				 * }
				 * 
				 * 
				 * rankList.add(info); }
				 */

				String url = String
						.format(UrlConfig
								.getUrlByKey(UrlConfig.GetExpertMessageUrlKey),
								account.getUserId(), cinfo.getId());
				br = HttpRequest.DoHttpRequest(url);
				if (br.isSuccess()) {
					JSONArray array = new JSONArray(br.getResponse());
					for (int i = 0; i < array.length(); i++) {
						JSONObject data = array.getJSONObject(i);
						ExpertMessage message = new ExpertMessage();
						message.setId(data.optInt("id"));
						message.setContent(data.optString("message"));
						int leaveUserId = data.optInt("senderId");
						message.setCreator(data.optString("sender"));
						message.setTime(data.optString("messageTime"));
						if (leaveUserId == cinfo.getId()) {
							message.setIcon(mApp.getIcon());
							String strUser = message.getCreator();
							String nickName = cinfo.getCustomNickName();
							if(StringUtil.isEmpty(strUser) || strUser.equals("null"))
							{
								strUser = cinfo.getCustomNickName();
								message.setCreator(strUser);
							}
							if(StringUtil.isEmpty(strUser) || strUser.equals("null"))
							{
								if (!data.isNull("senderMobile"))
									strUser = data.getString("senderMobile");
								message.setCreator(strUser);
							}
						} else {
							message.setCreator("我");
							message.setIcon(account.getOwerIcon());
						}
						rankList.add(message);
					}
				}
				mApp.setLstMessage(rankList);
			} else {
				mApp = null;
			}

		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public SalaryInfo getSalaryInfo(Context context) {
		SalaryInfo mApp = new SalaryInfo();
		try {
			String userId = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_UserId_Key, "");
			String firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.ManageSalaryUrlKey);
			firendUrl += "?userId=" + userId;
			BaseResp br = HttpRequest.DoHttpRequest(firendUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				if (respsonObject != null && !respsonObject.isNull("self")) {
					JSONObject selfObj = respsonObject.getJSONObject("self");
					mApp.setSalary(selfObj.getInt("salary"));
					mApp.setRank(selfObj.getInt("ranking"));
				}

				if (respsonObject != null && !respsonObject.isNull("rank")) {
					JSONArray respsonList = respsonObject.getJSONArray("rank");
					List<RankInfo> rankList = new ArrayList<RankInfo>();
					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject obj = respsonList.getJSONObject(i);
						RankInfo info = new RankInfo();
						info.setName(obj.getString("nickName"));
						info.setSalary(obj.getInt("salary"));
						rankList.add(info);
					}

					mApp.setRankList(rankList);
				}

			}
		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public boolean queryCustomInfo(Context context, CustomInfo cinfo) {
		boolean result = false;
		try {
			// String mobile = SharedPreferencesUtil.getValue(context,
			// SharedKey.Shared_Mobile_Key, "");
			String firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.ManageCustomInfoUrlKey);
			firendUrl += "?mobile=" + cinfo.getTianYi();// + "&id=" +
														// cinfo.getId();
			BaseResp br = HttpRequest.DoHttpRequest(firendUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				cinfo.setSex(respsonObject.getString("gender"));
				cinfo.setMode(respsonObject.getString("userAgent"));
				cinfo.setState(respsonObject.getString("state"));
				if (!respsonObject.isNull("basePreferName"))
					cinfo.setPackages(respsonObject.getString("basePreferName"));
				else
					cinfo.setPackages("(未知)");
				cinfo.setAverage_gprs(respsonObject.getString("avgVolume"));
				if (!respsonObject.isNull("usedVolume"))
					cinfo.setPackage_gprs(respsonObject.getString("usedVolume"));
				else
					cinfo.setPackage_gprs("(未知)");

				// cinfo.setPackage_gprs(respsonObject.getString("preferVolume"));
				cinfo.setOutPackage_gprs(respsonObject
						.getString("expVolumePacket"));
				if (!respsonObject.isNull("proportion"))
					cinfo.setProportion((int) (respsonObject
							.getDouble("proportion") * 100));
				if (!respsonObject.isNull("os")) {
					if (respsonObject.getString("os").equals("Andriod")
							|| respsonObject.getString("os").equals("andriod"))
						cinfo.setOs("Android");
					else
						cinfo.setOs(respsonObject.getString("os"));
				} else {
					cinfo.setOs("(未知)");
				}
				/*
				 * cinfo.setPackages(respsonObject.getString("package"));
				 * cinfo.setSex(respsonObject.getString("sex"));
				 * cinfo.setPackage_gprs(respsonObject.getInt("package_gprs"));
				 * cinfo.setOnlineTime(respsonObject.getString("onlineTime"));
				 * cinfo.setPrecinct(respsonObject.getString("precinct"));
				 * cinfo.setCounty(respsonObject.getString("county"));
				 * cinfo.setState(respsonObject.getString("state"));
				 * cinfo.setLastMonthAverage_gprs(respsonObject
				 * .getInt("lastMonthAverage_gprs"));
				 * cinfo.setAverage_gprs(respsonObject.getInt("average_gprs"));
				 * cinfo.setRecommend(respsonObject.getInt("recommend"));
				 * cinfo.setGprs_used(respsonObject.getInt("gprs_used"));
				 * cinfo.setOutPackage_gprs(respsonObject
				 * .getInt("outPackage_gprs"));
				 */
				result = true;
			}

			firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.ManageAnalysisInfoUrlKey);
			firendUrl += "?mobile=" + cinfo.getTianYi();
			BaseResp br1 = HttpRequest.DoHttpRequest(firendUrl);
			if (br1.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br1.getHttpResult());
				JSONArray respsonList = jsonObject.getJSONArray("response");
				if (respsonList != null && respsonList.length() > 0) {
					List<AnalysisInfo> rankList = new ArrayList<AnalysisInfo>();
					cinfo.setAnalysisList(rankList);

					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject obj = respsonList.getJSONObject(i);
						AnalysisInfo info = new AnalysisInfo();
						info.setId(obj.getInt("id"));
						info.setName(obj.getString("name"));
						rankList.add(info);
					}
				}
				result = true;
			}
		} catch (Exception e) {
			result = false;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return result;
	}

	private String genUserName(JSONObject obj) {
		if (obj == null)
			return "";
		String userName = "";
		String mobile = "";
		try {
			if (!obj.isNull("userName"))
				userName = obj.getString("userName");

			if (!obj.isNull("mobile"))
				mobile = obj.getString("mobile");

			String nickName = "";
			if (!obj.isNull("nickName"))
				nickName = obj.getString("nickName");

			userName = mobile;
			if (!StringUtil.isEmpty(nickName)) {
				userName = mobile + " (" + nickName + ")";
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userName;
	}
	
	public List<ShareGroupInfo> getShareGroup(Context context)
	{
		List<ShareGroupInfo> mApps = new ArrayList<ShareGroupInfo>();
		
		String userId = SharedPreferencesUtil.getValue(context,
				SharedKey.Shared_UserId_Key, "");
		String firendUrl = UrlConfig
				.getUrlByKey(UrlConfig.ShareGroupInfoUrlKey);
		firendUrl += "?userId="+ userId;
		try {
			
			BaseResp br = HttpRequest.DoHttpRequest(firendUrl);
			if (br.isSuccess()) {
				JSONObject jsonObject;
				jsonObject = new JSONObject(br.getHttpResult());
				JSONArray respsonArray = jsonObject.getJSONArray("response");
				if (respsonArray != null && respsonArray.length() > 0) {

					for (int i = 0; i < respsonArray.length(); i++) {
						JSONObject obj = respsonArray.getJSONObject(i);
						if(!obj.isNull("object"))
						{
							ShareGroupInfo sinfo = new ShareGroupInfo();
							mApps.add(sinfo);
							sinfo.setGroupName(obj.getString("groupName"));
							JSONArray objectArray = obj.getJSONArray("object");
							if (objectArray != null && objectArray.length() > 0) {
								List<CustomInfo> rankList = new ArrayList<CustomInfo>();
								sinfo.setCustoms(rankList);
								for (int j = 0; j < objectArray.length(); j++) {
									JSONObject objCust = objectArray.getJSONObject(j);
									CustomInfo info = new CustomInfo();
									info.setName(genUserName(objCust));
									info.setTianYi(objCust.getString("mobile"));

									if (!objCust.isNull("avgVolume"))
										info.setPackage_gprs(objCust.getString("avgVolume")+"M");
									else
										info.setPackage_gprs("(未知)");
									
									if (!objCust.isNull("flag"))
									{
										String flag = objCust.getString("flag");
										if(flag.equals("1"))
											info.setInvited(true);
									}
									
									rankList.add(info);
								}
									
							}
						}
					}
					
				}
				
			}
			else
			{
				mApps = null;
			}
		} catch (Exception e) {
			mApps = null;
			e.printStackTrace();
		}
		
//		mApps.clear();
//		ShareGroupInfo sgi1 = new ShareGroupInfo();
//		mApps.add(sgi1);
//		sgi1.setGroupName("ShareGroupInfo1111");
//		List<CustomInfo> cinfos1 = new ArrayList<CustomInfo>();
//		sgi1.setCustoms(cinfos1);
//		CustomInfo c1 = new CustomInfo();
//		c1.setTianYi("1801111111");
//		c1.setPackage_gprs("100000");
//		cinfos1.add(c1);
//		CustomInfo c2 = new CustomInfo();
//		c2.setTianYi("18022222222");
//		c2.setPackage_gprs("200000");
//		cinfos1.add(c2);
//		CustomInfo c3 = new CustomInfo();
//		c3.setTianYi("18033333333");
//		c3.setPackage_gprs("300000");
//		cinfos1.add(c3);
//		
//		ShareGroupInfo sgi2 = new ShareGroupInfo();
//		mApps.add(sgi2);
//		sgi2.setGroupName("ShareGroupInfo222");
//		List<CustomInfo> cinfos2 = new ArrayList<CustomInfo>();
//		sgi2.setCustoms(cinfos2);
//		CustomInfo c4 = new CustomInfo();
//		c4.setTianYi("18044444444");
//		c4.setPackage_gprs("400000");
//		cinfos2.add(c4);
//		CustomInfo c5 = new CustomInfo();
//		c5.setTianYi("18055555555");
//		c5.setPackage_gprs("500000");
//		cinfos2.add(c5);
//		CustomInfo c6 = new CustomInfo();
//		c6.setTianYi("18066666666");
//		c6.setPackage_gprs("600000");
//		cinfos2.add(c6);
		
		return mApps;
	}	
	/**
	 * 修改分享时获取我的客户使用接口获取
	 * @param context
	 * @return
	 */
	/*
	public List<ShareGroupInfo> getShareGroup(Context context)
	{
		List<ShareGroupInfo> mApps = new ArrayList<ShareGroupInfo>();
		try {
			
			List<ManageGroupInfo> manageGropInfoList = getGroups(context);
			
			if (manageGropInfoList!=null){
				ManageGroupInfo manageGroupInfo = null;
				List<ManageClientInfo> manageClientInfoList = null;
				ManageClientInfo manageClientInfo = null;
				for (int i = 0; i < manageGropInfoList.size(); i++) {
					manageGroupInfo = manageGropInfoList.get(i);
					ShareGroupInfo sinfo = new ShareGroupInfo();
					mApps.add(sinfo);
					sinfo.setGroupName(manageGroupInfo.getName());//groupName
					List<CustomInfo> rankList = new ArrayList<CustomInfo>();
					sinfo.setCustoms(rankList);
					
					manageClientInfoList = loadClients(context, manageGroupInfo.getId());
					if (manageClientInfoList!=null){
						for(int j = 0; j < manageClientInfoList.size(); j++) {
							manageClientInfo = manageClientInfoList.get(j);
							
							CustomInfo info = new CustomInfo();
							info.setName(manageClientInfo.getName());
							info.setTianYi(manageClientInfo.getMobile());
							info.setPackage_gprs(manageClientInfo.getFlow()+"M");
							
							rankList.add(info);
						}
					}
				}
			}
			else
			{
				mApps = null;
			}
		} catch (Exception e) {
			mApps = null;
			e.printStackTrace();
		}
		
		return mApps;
	}
*/
	
	public ManageInfo getManageInfo(Context context) {
		ManageInfo mApp = new ManageInfo();
		try {
			String userId = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_UserId_Key, "");
			String firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.ManageManageInfoUrlKey);
			firendUrl += "?orderType=" + CustomInfo.SortType + "&userId="
					+ userId;
			BaseResp br = HttpRequest.DoHttpRequest(firendUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				mApp.setHasClaimedNum(respsonObject.getInt("count"));
				mApp.setStillCanClaim(respsonObject.getInt("leftCount"));
				List<CustomInfo> rankList = new ArrayList<CustomInfo>();
				mApp.setCustoms(rankList);

				JSONArray respsonList = respsonObject
						.getJSONArray("joinUserList");
				if (respsonList != null && respsonList.length() > 0) {

					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject obj = respsonList.getJSONObject(i);
						CustomInfo info = new CustomInfo();
						info.setName(genUserName(obj));
						info.setTianYi(obj.getString("mobile"));
						info.setMode(obj.getString("userAgent"));
						info.setBaseLine(obj.getString("baseVal")+"M");
						info.setMessageTime(obj.optString("lastMessageTime"));
						if (!obj.isNull("userName"))
							info.setCustomNickName(obj.getString("userName"));

						if (!obj.isNull("nickName"))
							info.setCustomNickName(obj.getString("nickName"));
						
						if (!obj.isNull("usedVolume"))
							info.setPackage_gprs(obj.getString("usedVolume")+"M");
						else
							info.setPackage_gprs("(未知)");

						if (!obj.isNull("os")) {
							if (obj.getString("os").equals("Andriod")
									|| obj.getString("os").equals("andriod"))
								info.setOs("Android");
							else
								info.setOs(obj.getString("os"));
						} else {
							info.setOs("(未知)");
						}
						if (!obj.isNull("crtDt"))
							info.setJoinTime(obj.getString("crtDt"));
						if (!obj.isNull("icon")) {
							info.setIcon(obj.getString("icon"));
							// info.setIcon("http://image215.poco.cn/mypoco/myphoto/20091219/19/53592096200912191857561188544515496_009_640.jpg");
						} else {
							// info.setIcon("http://image215.poco.cn/mypoco/myphoto/20091219/19/53592096200912191857561188544515496_009_640.jpg");
						}
						info.setMessageCount(obj.getInt("noReads"));
						info.setInvited(true);
						rankList.add(info);
					}

				}

				JSONArray noJoinUserList = respsonObject
						.getJSONArray("noJoinUserList");
				if (noJoinUserList != null && noJoinUserList.length() > 0) {

					for (int i = 0; i < noJoinUserList.length(); i++) {
						JSONObject obj = noJoinUserList.getJSONObject(i);
						CustomInfo info = new CustomInfo();
						info.setName(genUserName(obj));
						info.setTianYi(obj.getString("mobile"));
						info.setMode(obj.getString("userAgent"));
						info.setBaseLine(obj.getString("baseVal")+"M");

						if (!obj.isNull("userName"))
							info.setCustomNickName(obj.getString("userName"));

						if (!obj.isNull("nickName"))
							info.setCustomNickName(obj.getString("nickName"));
						
						if (!obj.isNull("usedVolume"))
							info.setPackage_gprs(obj.getString("usedVolume")+"M");
						else
							info.setPackage_gprs("(未知)");

						if (!obj.isNull("os")) {
							if (obj.getString("os").equals("Andriod")
									|| obj.getString("os").equals("andriod"))
								info.setOs("Android");
							else
								info.setOs(obj.getString("os"));
						} else {
							info.setOs("(未知)");
						}
						if (!obj.isNull("crtDt"))
							info.setJoinTime(obj.getString("crtDt"));
						if (!obj.isNull("icon"))
							info.setIcon(obj.getString("icon"));
						if (!obj.isNull("noReads"))
							info.setMessageCount(obj.getInt("noReads"));
						rankList.add(info);
					}

				}
			} else {
				mApp = null;
			}
		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public SalaryInfo querySalaryInfo(Context context, DateParams params) {
		SalaryInfo mApp = new SalaryInfo();
		try {
			String mobile = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_Mobile_Key, "");
			String firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.ManageQeurySalaryUrlKey);
			firendUrl += "?mobile=" + mobile + "&startTime="
					+ params.getBeginStr() + "&endTime=" + params.getEndStr();
			BaseResp br = HttpRequest.DoHttpRequest(firendUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				if (respsonObject != null && !respsonObject.isNull("self")) {
					JSONObject selfObj = respsonObject.getJSONObject("self");
					mApp.setSalary(selfObj.getInt("salary"));
					mApp.setRank(selfObj.getInt("ranking"));
				}

				if (respsonObject != null && !respsonObject.isNull("rank")) {
					JSONArray respsonList = respsonObject.getJSONArray("rank");
					List<RankInfo> rankList = new ArrayList<RankInfo>();
					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject obj = respsonList.getJSONObject(i);
						RankInfo info = new RankInfo();
						info.setName(obj.getString("nickName"));
						info.setSalary(obj.getInt("salary"));
						rankList.add(info);
					}
					mApp.setRankList(rankList);
				} else {
					mApp = null;
				}
			}
		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public List<ManageGroupInfo> getGroups(Context context) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.ManageGroupsUrlKey),
					account.getUserId());
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				List<ManageGroupInfo> groups = new ArrayList<ManageGroupInfo>();
				JSONArray array = new JSONArray(br.getResponse());
				for (int i = 0; i < array.length(); i++) {
					JSONObject data = array.optJSONObject(i);
					ManageGroupInfo group = new ManageGroupInfo();
					String id = data.optString("id");
					group.setId(id);
					group.setName(data.optString("name"));
					group.setCustomCount(data.optInt("num"));
					if (group.isSystem())
						groups.add(0, group);
					else
						groups.add(group);
				}
				return groups;
			} else {
				errorCode = Integer.valueOf(br.getErrorCode());
			}
		} catch (Exception e) {

		}
		return null;
	}

	public boolean addGroup(Context context, String name) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.ManageAddGroupUrlKey),
					account.getUserId());
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("groupName", name);
			BaseResp br = HttpRequest.DoHttpRepuestPost(url, params);
			return br.isSuccess();
		} catch (Exception e) {

		}
		return false;
	}

	public boolean removeGroup(Context context, int groupId) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.ManageRemoveGroupUrlKey),
					account.getUserId(), groupId);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			return br.isSuccess();
		} catch (Exception e) {

		}
		return false;
	}

	public List<ManageClientInfo> loadClients(Context context, String groupId) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.ManageGetClientsUrlKey),
					account.getUserId(), groupId);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				List<ManageClientInfo> clients = new ArrayList<ManageClientInfo>();
				JSONArray array = new JSONArray(br.getResponse());
				for (int i = 0; i < array.length(); i++) {
					JSONObject clientData = array.optJSONObject(i);
					ManageClientInfo client = new ManageClientInfo();
					client.setName(clientData.optString("username"));
					client.setMobile(clientData.optString("mobile"));
					client.setFlow(clientData.optLong("avgvolume"));
					clients.add(client);
				}
				return clients;
			} else {
				errorCode = Integer.valueOf(br.getErrorCode());
			}
		} catch (Exception e) {

		}
		return null;
	}

	public boolean addClientsToGroup(Context context,
			List<ManageClientInfo> clients, int groupId) {
		try {
			lastErrorMessage = "";
			Account account = AccountMgr.readAccountInfo(context);
			StringBuilder builder = new StringBuilder();
			for (ManageClientInfo client : clients) {
				builder.append(',');
				builder.append(client.getMobile());
			}
			String mobiles = builder.substring(1);
			String url = String.format(UrlConfig
					.getUrlByKey(UrlConfig.ManageAddClientsToGroupUrlKey),
					account.getUserId(), groupId, mobiles);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.getErrorCode().equals("417"))
				lastErrorMessage = "您选择的客户已在该分组";
			return br.isSuccess();
		} catch (Exception e) {

		}
		return false;
	}

	public boolean moveClients(Context context, List<ManageClientInfo> clients,
			int groupId, int originalGroupId) {
		try {
			lastErrorMessage = "";
			Account account = AccountMgr.readAccountInfo(context);
			StringBuilder builder = new StringBuilder();
			for (ManageClientInfo client : clients) {
				builder.append(',');
				builder.append(client.getMobile());
			}
			String mobiles = builder.substring(1);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.ManageMoveClients),
					account.getUserId(), groupId, mobiles, originalGroupId);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.getErrorCode().equals("417"))
				lastErrorMessage = "您选择的客户已在该分组";
			return br.isSuccess();
		} catch (Exception e) {

		}
		return false;
	}

	public boolean removeClients(Context context,
			List<ManageClientInfo> clients, int groupId) {
		try {
			Account account = AccountMgr.readAccountInfo(context);
			StringBuilder builder = new StringBuilder();
			for (ManageClientInfo client : clients) {
				builder.append(',');
				builder.append(client.getMobile());
			}
			String mobiles = builder.substring(1);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.ManageRemoveClients),
					account.getUserId(), groupId, mobiles);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			return br.isSuccess();
		} catch (Exception e) {

		}
		return false;
	}
}
